﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;

namespace TestStatuses
{
    public class Handler : IHttpHandler
    {

        private JavaScriptSerializer serializer;
        private string SmokeTestsNetworkDriveMapping = WebConfigurationManager.AppSettings["smoketests_dir"];
        private static object lockObject = new object();
        
        public Handler()
        {
            serializer = new JavaScriptSerializer();
        }


        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";

            string json = serializer.Serialize(GetFromDisk(SmokeTestsNetworkDriveMapping));
            context.Response.Write(string.Format("{0}({1});", context.Request["callback"], json));
        }

        private static List<string> GetFromDisk(string smokeTestsNetworkDriveMapping)
        {            
            List<string> jsonResults = new List<string>();
            FileInfo newestLogFile = null;
            DateTime newestLogDate = DateTime.MinValue;
            DirectoryInfo directoryInfo = new DirectoryInfo(smokeTestsNetworkDriveMapping);
            
            try
            {
                FileInfo[] fileInfo = directoryInfo.GetFiles();
                foreach (FileInfo info in fileInfo)
                {
                    if (info.CreationTimeUtc > newestLogDate)
                    {
                        newestLogDate = info.CreationTimeUtc;
                        newestLogFile = info;
                    }
                }
                if (newestLogFile != null)
                {
                    TextReader reader, memoryReader;
                    string relevantSection;
                    
                    lock (lockObject)
                    {
                        using (reader = new StreamReader(newestLogFile.OpenRead()))
                        {
                            string fullContent = reader.ReadToEnd();
                            string[] contentSections = fullContent.Split(new[] { "Final Smoke Testing" }, StringSplitOptions.RemoveEmptyEntries);
                            relevantSection = contentSections[contentSections.Length - 1];
                        }
                    }

                    using(memoryReader = new StreamReader(new MemoryStream(Encoding.Default.GetBytes(relevantSection))))
                    {
                        string currentLine;
                        while ((currentLine = memoryReader.ReadLine()) != null)
                        {
                            if (currentLine.Contains("http") && !currentLine.Contains("OK"))
                            {
                                jsonResults.Add(currentLine);
                            }
                        }
                    }
                    
                }
            }
            catch (IOException exception)
            {
                jsonResults.Clear();
                jsonResults.Add("SMARTBOARD ERROR: " + exception.Message);
            }

            return jsonResults;
        }



        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}